<template>
	<view class="padding-bt-100 mainPage" style="padding-top: 0">
		<view class="padding padding-bottom-xl">
			<view class="address padding bg-white radius-xl margin-bottom">
				<view class="info" @click="toUrl('/pages/user/address/list?pageType=order')">
					<view class="username margin-bottom-xs" v-if="address.id">
						<text class="text-bold text-black">{{ address.nickname }}</text>
						<text class="padding-left">{{ address.phone }}</text>
					</view>
					<view class="detail text-sm text-gray">
						{{ address.address || '请选择地址' }}
					</view>
				</view>
				<view class="more" @click="toUrl('/pages/user/address/list?pageType=order')">
					<text class="cuIcon-right text-bold"></text>
				</view>
			</view>

			<view class="padding bg-white radius-xl margin-bottom">
				<view class="project-list padding-bottom-xs">
					<view class="item radius-lg padding-tb"
					:class="projects.length - 1 != index ? 'solid-bottom' : ''"
					v-for="(item,index) in projects" :key="index">
						<image :src="item.image" mode="aspectFill" class="img"></image>
						<view class="probox">
							<view class="title text-bold text-black margin-bottom-xs">
								<text>{{item.name}}</text>
								<view class="text-sm text-right cost text-red">
									<text class="text-bold">¥</text>
									<text class="text-lg text-bold">{{item.price }}</text>
								</view>
							</view>
							<view class="text-gray margin-bottom-sm text-sm">{{item.description }}</view>
							<view class="price flex flex-wrap">
								<view class="time basis-sm text-sm">
									<text class="cuIcon-timefill text-lg themeColor"></text>
									<text class="padding-left-mn">{{item.duration }}分钟</text>
								</view>
								<view class="basis-lg text-right liji">
									<u-number-box
										button-size="20"
										v-model="item.num"
										min="0"
										style="float: right;">
									</u-number-box>
								</view>
							</view>
						</view>
					</view>
				</view>

				<view class="servicePartner grid col-2 margin-bottom">
					<view class="">服务客服</view>
					<view class="text-right crow">
						<view class="cu-avatar sm round margin-left" :style="{backgroundImage: 'url('+partnerInfo.image+')'}"></view>
						<text class="padding-lr-sm">{{partnerInfo.nickname}}</text>
					</view>
				</view>

				<view class="serviceTime grid col-2">
					<view class="">服务时间</view>
					<view class="text-right" @click="toChangeServeTime()">
						<text class="padding-left-sm themeColor">{{ serveTime || '请选择服务时间'}}</text>
						<text class="cuIcon-right"></text>
					</view>
				</view>
			</view>

			<!-- 出行方式 -->
			<view class="travel padding bg-white radius-xl margin-bottom">
				<view class="grid col-2">
					<view class="text-black text-bold">出行方式</view>
					<view class="text-right" @click="toChangeTravel()">
						<text class="themeColor">{{ selectTravel.label }}</text>
						<text class="cuIcon-right"></text>
					</view>
				</view>
				<view class="tips padding-sm" v-if="selectTravel.value">
          全程共{{ totalkm }}km，{{ selectTravel.name }}收取来回车费，起步{{ selectTravel.start_price }}元/{{ selectTravel.start_km }}km,超出1km,收取{{ selectTravel.over_km_price }}元
				</view>
				<view class="fare">
					<label>车费</label>
					<view class="text-red margin-right-xs text-bold">￥{{ totalPrice }}</view>
				</view>
			</view>

<!--			<view class="coupon padding bg-white radius-lg margin-tb"  @click="toSetCouponShow" v-if="couponList">-->
<!--				<text>选择优惠券</text>-->
<!--				<view class="selected" @click="toSetCouponShow">-->
<!--					<text class="text-orange">-￥20.50</text>-->
<!--					<text class="cuIcon-right"></text>-->
<!--				</view>-->
<!--			</view>-->

			<view class="remark padding bg-white radius-xl">
				<view>
					<textarea maxlength="255"  placeholder="在此输入备注信息" v-model="form.remark"></textarea>
				</view>
			</view>
		</view>

		<view class="cu-bar bg-white tabbar shop foot grid col-2">
			<view class="padding-left">
				合计：<text class="text-red text-lg text-bold">¥{{ amount || '0.00' }}</text>
			</view>
			<view class="reservation text-right padding-right">
				<button class="cu-btn round china-btn-bg " @click="getOrderData('post')">
					<text class="padding-lr-xl">立即下单</text>
				</button>
			</view>
		</view>

    <u-select
        cancel-color="var(--theme-color)"
        confirm-color="var(--theme-color)"
        mode="single-column" v-model="travelShow" :list="travelsList" @confirm="pickerPopup"></u-select>
<!--		<serviveTime :show="serviceTimeShow" :partnerId="form.partnerId" @serviceTimePopup="serviceTimePopup" v-if="serviceTimeShow"/>-->

		<payType
			:show="payTypeShow"
      :orderData="orderData"
			@payCallBack="payCallBack"
			:referParams="form"
			source='partner'/>

		<myCoupon :show="couponShow" :list="couponList" @couponPopup="couponPopup"/>
    <u-popup v-model="dateShow" mode="bottom" border-radius="14">
      <div class="date-picker-title">
        <span>选择时间</span>
        <span class="confirm-text" @click="confirmDate">确定</span>
      </div>
      <div class="date-picker-content">
        <div class="date-picker-slide">
          <div
              v-for="item in dayList"
              :key="item.day"
              @click="changeDay(item.value)"
              :class="['date-slide-item',item.value === activeDay ? 'active' :'']">
            {{ item.day }}
          </div>
        </div>
        <div class="date-time-list">
          <div
              @click="activeTime = item"
              :class="['date-time-item',item === activeTime ? 'active' :'']"
              v-for="item in timeList" :key="item">
            {{ item }}
          </div>
        </div>
      </div>
    </u-popup>

		<Loading v-if="pageLoading"/>
	</view>
</template>

<script>
	import serviveTime from './modules/serviceTime.vue'; // 服务时间
	import payType from '@/components/payType/payType.vue'; // 服务时间
	import myCoupon from '@/components/myCoupon/myCoupon.vue'; // 优惠券
  import dayjs from 'dayjs'
	export default {
		components: {serviveTime,payType,myCoupon},
		data() {
			return {
				pageLoading:false,
				form:{
					partnerId:0,
					addressId:0,
					serviveTime:[],
					remark:'',
					couponId:0
				},
				orderData:{},
				address: {},
        travelName: '',
        travelDesc: '',
        travelsList: [],
				travels: [
				],
				projects: [],//项目信息
				partnerInfo: {},//客服信息
				selectTravel: {},//选中出行方式
        serveTime: '',
				travelShow:false,//出行方式弹出层
				serviceTimeShow:false,//服务时间弹出层
				payTypeShow:false,//支付方式弹出层
				couponShow:false,//优惠券弹出层
				couponList:[
					{
						reduce_price:'10.50',
						name:'满减券',
						min_price:'200',
						end_time:'2023-09-18',
						is_usable:10,
						user_coupon_id:1
					},
					{
						reduce_price:'20.50',
						name:'满减券',
						min_price:'500',
						end_time:'2023-09-18',
						is_usable:20,
						user_coupon_id:2
					}
				],
        dateShow: false,
        activeDay: dayjs().format('YYYY-MM-DD'),
        activeTime: '08:00-08:30',
        // 日期 今天 明天 后天 计算具体月日
        dayList: [
          {id: 0, day: `今天${dayjs().format('MM月DD日')}`, value: dayjs().format('YYYY-MM-DD')},
          {id: 1, day: `明天${dayjs().add(1, 'day').format('MM月DD日')}`, value: dayjs().add(1, 'day').format('YYYY-MM-DD')},
          {id: 2, day: `后天${dayjs().add(2, 'day').format('MM月DD日')}`, value: dayjs().add(2, 'day').format('YYYY-MM-DD')},
        ],
        timeList: [

        ],
			};
		},
		onLoad(options) {
      this.form.partnerId = options.partnerId;
      this.projects = JSON.parse(options.projects);
      for (let i = 0; i < this.projects.length; i++) {
        const project = this.projects[i];
        this.$http.getProjectDetail({
          id: project.project_id
        }).then(res => {
          this.projects[i] = {
            ...res,
            image:  res.image,
            num: project.num
          }
          console.log(this.projects)
        })
      }
      let that = this
			uni.$on('address',(res)=>{
        console.log(res,'地址')
        that.address = res
			})
      this.$http.getTravelModeList().then(res => {
        this.travelsList = res.map(item => {
          return {
            label: item.name,
            value: item.id,
            ...item
          }
        })
        if (this.travelsList.length) {
          this.selectTravel = {
            label: this.travelsList[0].name,
            value: this.travelsList[0].id,
            ...this.travelsList[0],
          }
        }
        console.log('this.travelsList',this.travelsList)
      })
      this.$http.getTechnicianDetail({
        id: options.partnerId
      }).then(res => {
        this.partnerInfo = res
      })
      // 根据当前时间计算日期 如果超过晚上8点 则默认选择明天 并且仅展示明天的列表
      const hour = dayjs().hour()
      if (hour >= 20) {
        this.activeDay = dayjs().add(1, 'day').format('YYYY-MM-DD')
        this.dayList = [
          {id: 0, day: `明天${dayjs().add(1, 'day').format('MM月DD日')}`, value: dayjs().add(1, 'day').format('YYYY-MM-DD')},
          {id: 1, day: `后天${dayjs().add(2, 'day').format('MM月DD日')}`, value: dayjs().add(2, 'day').format('YYYY-MM-DD')},
        ]
      } else {
        this.activeDay = dayjs().format('YYYY-MM-DD')
        this.dayList = [
          {id: 0, day: `今天${dayjs().format('MM月DD日')}`, value: dayjs().format('YYYY-MM-DD')},
          {id: 1, day: `明天${dayjs().add(1, 'day').format('MM月DD日')}`, value: dayjs().add(1, 'day').format('YYYY-MM-DD')},
          {id: 2, day: `后天${dayjs().add(2, 'day').format('MM月DD日')}`, value: dayjs().add(2, 'day').format('YYYY-MM-DD')},
        ]
      }
		},
		methods:{
			getOrderData(){
        const userInfo = uni.getStorageSync('userInfo') || {}
        if (!userInfo.id) {
          uni.showToast({
            title: '请先登录',
            icon: 'none'
          })
          return;
        }
        if (!this.address.id) {
          uni.showToast({
            title: '请选择地址',
            icon: 'none'
          })
          return
        }
        if (this.projects.every(item => item.num === 0)) {
          uni.showToast({
            title: '请选择项目',
            icon: 'none'
          })
          return
        }
        if (!this.selectTravel.id) {
          uni.showToast({
            title: '请选择出行方式',
            icon: 'none'
          })
          return
        }
        this.orderData.pay_amount = this.amount
        this.payTypeShow = true
			},
			payCallBack(pay_type){
        uni.showLoading({
          title: '请等待'
        })
        let that = this
        this.$http.createOrder({
          address: JSON.stringify(this.address),
          staff_id: this.form.partnerId,
          member_id: uni.getStorageSync('userInfo').id,
          projects: this.projects,
          travel_mode_id: this.selectTravel.id,
          travel_mode_name: this.selectTravel.name,
          travel_mode_fee: this.totalPrice,
          start_time: this.serveTime,
          end_time: this.serveTime,
          remark: this.form.remark,
          pay_amount: this.amount,
          pay_type: pay_type,
          body: '服务订单'
        }).then(res => {
          wx.requestPayment({
            timeStamp: res.timestamp,
            nonceStr: res.nonce_str,
            package: res.package,
            signType: res.signType,
            paySign: res.paySign,
            success () {
              that.$http.updateOrderPayStatus({
                order_no: res.order_no,
              }).then(res2 => {
                uni.redirectTo({
                  url: '/pages/order/payment/payment'
                })
              })
            },
            fail (res) {
              uni.reLaunch({
                url: '/pages/order/list'
              })
            }
          })
        })
			},
			serviceTimePopup(e){
				if(e.type=='confirm'){
					this.form.serviveTime = e.data;
					this.getOrderData('get');
				}
				this.serviceTimeShow = false
			},
			pickerPopup(e){
        console.log(e)
				if(e.type=='confirm'){
					this.selectTravel = e[0];
				}
				this.travelShow = false;
			},
			couponPopup(e){
				this.form.couponId = e.data;
				this.couponShow = false;
				this.getOrderData('get');
			},
			toChangeTravel(){
				this.travelShow = true;
			},
			toChangeServeTime(){
        this.dateShow = true
        this.activeDay = this.serveTime.split(' ')[0]
        this.activeTime = this.serveTime.split(' ')[1]
        this.changeDay(this.activeDay || this.dayList[0].value)
			},
      changeDay(value) {
        this.activeDay = value
        let timeList = []
        // 如果activeDay是当天 则只能选择当前时间之后的时间 如果是后天 则可以选择所有时间
        const now = dayjs().format('YYYY-MM-DD')
        if (value === now) {
          // 当天根据当前时间计算
          const hour = dayjs().hour()
          const minute = dayjs().minute()
          let start = 8
          if (hour > 8) {
            start = hour
            if (minute > 30) {
              start++
            }
          }

          for (let i = start; i < 21; i++) {
            timeList.push(`${i}:00-${i}:30`)
            timeList.push(`${i}:30-${i+1}:00`)
          }
        } else {
          // 非当天 使用循环插入时间 早上8点到晚上8点
          for (let i = 8; i < 21; i++) {
            timeList.push(`${i}:00-${i}:30`)
            timeList.push(`${i}:30-${i+1}:00`)
          }
        }
        this.timeList = timeList
        this.activeTime = timeList[0]

      },
			toSetCouponShow(){
				this.couponShow = true;
			},
      toUrl(page) {
        uni.navigateTo({
          url:page
        })
      },

      Rad(d) { //根据经纬度判断距离
        return d * Math.PI / 180.0;
      },
      getDistance(lat1, lng1, lat2, lng2) {
        console.log('lat1, lng1, lat2, lng2',lat1, lng1, lat2, lng2)
        if (!lat1 || !lng1 || !lat2 || !lng2) {
          return 0
        }
        if (lat1 == lat2 && lng1 == lng2) {
          return 0;
        }
        // lat1用户的纬度
        // lng1用户的经度
        // lat2客服的纬度
        // lng2客服的经度
        var radLat1 = this.Rad(lat1);
        var radLat2 = this.Rad(lat2);
        var a = radLat1 - radLat2;
        var b = this.Rad(lng1) - this.Rad(lng2);
        var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
        s = s * 6378.137;
        s = Math.round(s * 10000) / 10000;
        s = s.toFixed(2)
        console.log('经纬度计算的距离:' + s)
        return parseInt(s)
      },

      confirmDate() {
        this.dateShow = false
        this.serveTime = `${this.activeDay} ${this.activeTime}`
      },
		},
    computed: {
      totalkm() {
        // 根据address中的坐标
        console.log('sdaddd')
        return this.getDistance(this.address.latitude, this.address.longitude, this.partnerInfo.latitude, this.partnerInfo.longitude)
      },
      totalPrice() {
        let price = 0
        let totalkm = this.totalkm
        if (!totalkm) return 0
        console.log('totalkm',totalkm)
        if (this.selectTravel.value) {
          price+=Number(this.selectTravel.start_price)
          if (totalkm > this.selectTravel.start_km) {
            price += (totalkm - this.selectTravel.start_km) * Number(this.selectTravel.over_km_price)
          }
        }
        return price
      },
      addressText() {
        return this.address.province + this.address.city + this.address.area + this.address.address || '请选择地址'
      },
      amount() {
        let val = this.projects.reduce((total, item) => {
          return total + item.price * item.num
        }, 0)
        return val + this.totalPrice
      }
    }
	}
</script>

<style lang="less">

.date-picker-content {
  height: 500rpx;
  overflow: hidden;
  display: flex;
  background-color: rgb(242, 242, 242);
  .date-picker-slide {
    flex-shrink: 0;
    display: flex;
    flex-direction: column;
    align-items: center;
    .date-slide-item {
      font-size: 28rpx;
      color: #333333;
      padding: 13px 43px 13px 30px;
      &.active {
        background-color: #ffffff;
      }
    }
  }
  .date-time-list {
    height: 100%;
    flex-grow: 1;
    overflow: auto;
    background-color: #ffffff;
    .date-time-item {
      flex-shrink: 0;
      line-height: 80rpx;
      font-size: 28rpx;
      color: #333333;
      text-align: center;
      margin-bottom: 10px;
      &.active {
        color: #f15929
      }
    }
  }
}
.date-picker-title {
  padding: 17px 15px;
  background-color: rgb(242, 242, 242);
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 28rpx;
  color: #333333;
  .confirm-text {
    color: #f15929;
  }
}

.address{
	display: flex;
	justify-content: space-between;
	align-items: center;
}
.project-list{
	.item{
		display: flex;
		align-items: center;
		justify-content: space-between;
		flex-direction: row;
		height: 190upx;
		.img{
			width: 170upx;
			height: 140upx;
			border-radius: 10upx;
		}
		.probox{
			width: 70%;
			.title{
				display: flex;
				justify-content: space-between;
				align-items: baseline;
				.cost{
					width: 125upx;
				}
			}
		}
	}
}
.servicePartner{
	.crow{
		justify-content: flex-end;
	}
}
.goAddAddress{
	margin: auto;
}
.travel{
	.tips {
		background: #efefef;
		border-radius: 10rpx;
		margin-top: 20rpx;
		font-size: 24rpx;
		font-weight: 500;
		color: blcak;
		line-height: 36rpx;
	}

	.fare {
		display: flex;
		align-items: center;
		justify-content: space-between;
		font-size: 28rpx;
		margin-top: 20rpx;
	}
}
.remark{
	textarea{
		height: 100upx;
	}
}
.foot{
	height: 120upx;
}
.coupon{
	font-size: 14px;
	display: flex;
	justify-content: space-between;
	align-items: center;
}
</style>
